package project

import (
	"context"
	"encoding/json"
	"fmt"
	"gf-assistant/internal/common/factory"
	"gf-assistant/internal/project/parameter"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"reflect"
	"strings"
)

type MemberDao struct{}

func init() {
	memberDao := MemberDao{}
	factory.Put(reflect.TypeOf(memberDao).String(), &memberDao)
}
func (dao *MemberDao) DB() gdb.DB {
	return g.DB()
}
func (dao *MemberDao) ListMember(ctx context.Context, req *parameter.ListMemberReq) (members []*parameter.GetMemberRes) {
	parameters := make([]interface{}, 0)
	sql := `
		  select t.MEMBER_ID as MemberId,p.PROJECT_NAME as ProjectName,m.NICK_NAME as NickName,
		         ELT(FIELD(t.ENABLE_STATUS, 0, 1),'无效','有效')AS EnableStatusName,
		         pp.POSITION_NAME as PositionName,t.REMARK as Remark,
		         c.NICK_NAME as CreatedUserName,cm.NICK_NAME as UpdatedUserName,
				 DATE_FORMAT(t.CREATE_TIME,'%Y-%m-%d %T') as CreatedTime,
				 DATE_FORMAT(t.UPDATE_TIME,'%Y-%m-%d %T') as UpdatedTime
		  from PROJECT_MEMBER t 
		  join PROJECT_INFO p on t.PROJECT_ID=p.PROJECT_ID
		  join SYS_USER m on t.USER_ID=m.USER_ID
		  join PROJECT_POSITION pp on pp.POSITION_ID=t.POSITION_ID 
		  left join SYS_USER c on t.CREATE_USER=c.USER_ID
		  left join SYS_USER cm on t.USER_ID=cm.USER_ID
		  where t.PROJECT_ID=?
		  `
	parameters = append(parameters, req.ProjectId) //项目成员
	if req.NickName != "" {
		sql = sql + " and m.NICK_NAME like ?\n"
		parameters = append(parameters, "%"+strings.TrimSpace(req.NickName)+"%") //项目名称
	}

	resultList, err := g.DB().GetAll(ctx, sql, parameters)
	if err != nil {
		fmt.Printf("query faied, error:[%v]", err.Error())
		return
	}
	//遍历结构体切片
	for _, v := range resultList {
		member := parameter.GetMemberRes{}
		err = json.Unmarshal([]byte(v.Json()), &member)
		if err != nil {
			fmt.Println("JSON unmarshal error:", err)
		}
		members = append(members, &member)
	}
	return members
}
func (dao *MemberDao) ListPosition(ctx context.Context, req *parameter.ListPositionReq) (positions []*parameter.GetPositionRes) {
	sql := `
		  select t.POSITION_ID as Id,t.POSITION_NAME as Title
		  from PROJECT_POSITION t 
		  where t.ENABLE_STATUS=1
		  `
	resultList, err := g.DB().GetAll(ctx, sql)
	if err != nil {
		fmt.Printf("query faied, error:[%v]", err.Error())
		return
	}
	//遍历结构体切片
	for _, v := range resultList {
		position := parameter.GetPositionRes{}
		err = json.Unmarshal([]byte(v.Json()), &position)
		if err != nil {
			fmt.Println("JSON unmarshal error:", err)
		}
		positions = append(positions, &position)
	}
	return positions
}
func (dao *MemberDao) GetMemberSelected(ctx context.Context, req *parameter.ListMemberSelectedReq) (members []*parameter.GetMemberSelectedRes) {
	sql := `
		  select t.USER_ID as Value,t.NICK_NAME as Name
		  from SYS_USER t 
		  where t.ENABLE_STATUS=1
# 		  	and not exists(
# 		  	    select 1 
# 		  	    from PROJECT_MEMBER m 
# 		  		where t.USER_ID=m.USER_ID 
# 					and m.ENABLE_STATUS=1
# 					and m.PROJECT_ID=?
# 		  	)
		  `
	//resultList, err := g.DB().GetAll(ctx, sql, req.ProjectId)
	resultList, err := g.DB().GetAll(ctx, sql)
	if err != nil {
		fmt.Printf("query faied, error:[%v]", err.Error())
		return
	}
	//遍历结构体切片
	for _, v := range resultList {
		user := parameter.GetMemberSelectedRes{}
		err = json.Unmarshal([]byte(v.Json()), &user)
		if err != nil {
			fmt.Println("JSON unmarshal error:", err)
		}
		members = append(members, &user)
	}
	return members
}
func (dao *MemberDao) GetMemberCombox(ctx context.Context, req *parameter.GetMemberComboxReq) (members []*parameter.MemberComboxRes) {
	sql := `
		  select t.MEMBER_ID as Value,u.NICK_NAME as Name
		  from PROJECT_MEMBER t 
		  left join SYS_USER u on t.USER_ID = u.USER_ID
		  where t.ENABLE_STATUS=1
		  	and t.PROJECT_ID=?
		  order by u.NICK_NAME
		  `
	resultList, err := g.DB().GetAll(ctx, sql, req.ProjectId)
	if err != nil {
		fmt.Printf("query faied, error:[%v]", err.Error())
		return
	}
	//遍历结构体切片
	for _, v := range resultList {
		member := parameter.MemberComboxRes{}
		err = json.Unmarshal([]byte(v.Json()), &member)
		if err != nil {
			fmt.Println("JSON unmarshal error:", err)
		}
		members = append(members, &member)
	}
	return members
}
func (dao *MemberDao) CreateMember(tx gdb.TX, req *parameter.CreateMemberReq) {
	sql := `
			insert into PROJECT_MEMBER(USER_ID,PROJECT_ID,POSITION_ID,ENABLE_STATUS,REMARK,CREATE_TIME,CREATE_USER,UPDATE_TIME,UPDATE_USER)
			values (?,?,?,?,?,now(),?,now(),?)
			on duplicate key update 
				POSITION_ID=?,
				ENABLE_STATUS=1,
				REMARK=?,
				UPDATE_TIME=now(),
				UPDATE_USER=?
		  `
	if strings.Contains(req.UserIds, ",") {
		for _, v := range strings.Split(req.UserIds, ",") {
			_, _ = tx.Exec(sql, gconv.Uint(v), req.ProjectId, req.PositionId, 1, req.Remark, req.GetOperatorId(), req.GetOperatorId(),
				req.PositionId, req.Remark, req.GetOperatorId())
		}
	} else {
		_, _ = tx.Exec(sql, gconv.Uint(req.UserIds), req.ProjectId, req.PositionId, 1, req.Remark, req.GetOperatorId(), req.GetOperatorId(),
			req.PositionId, req.Remark, req.GetOperatorId())
	}
}
func (dao *MemberDao) DeleteMember(tx gdb.TX, req *parameter.DeleteMemberReq) {
	sql := `
			update PROJECT_MEMBER set 
				ENABLE_STATUS=0,
				UPDATE_TIME=now(),
				UPDATE_USER=?
			where MEMBER_ID=?
		  `
	_, err := tx.Exec(sql, req.GetOperatorId(), req.MemberId)
	if err != nil {
		panic("删除成员失败")
	}
}
